//
//  ETH+Web3.swift
//  XHWalletUtils
//
//  Created by xinph on 2020/5/16.
//  Copyright © 2020 xinph. All rights reserved.
//

import Foundation
import web3swift

extension ETH {
    /// 获取web3对象
    public func generateWeb3() -> web3? {
//        guard ETH.web3 == nil else { return ETH.web3 }
        /// 以太坊60 币种类型 BIP44 https://github.com/satoshilabs/slips/blob/master/slip-0044.md
//        guard let wallet = Manager.shared.wallets?[CoinBIP44.defaultETHPath], wallet != ETH.empty() as! ETH else {
//            return nil
//        }
        let web3 = Web3.InfuraRinkebyWeb3(accessToken: Config.default.accessToken)
//        let web3 = accessWeb3OnDiffrenceNetwork(wallet.network)
        ETH.web3 = web3
        let keystoreManager: KeystoreManager
        guard let keystore = self.keystore else { return web3 }
        if self.isHDWallet {
            self.ethKeystore = BIP32Keystore(keystore)!
            keystoreManager = KeystoreManager([self.ethKeystore!])
        } else {
            let keystore = EthereumKeystoreV3(keystore)!
            keystoreManager = KeystoreManager([keystore])
        }
        web3.addKeystoreManager(keystoreManager)
        return web3
    }

    /// 根据不同网络配置获取web3对象
    /// - Parameter network: 不同的网络环境
    /// - Returns: web3
    private func accessWeb3OnDiffrenceNetwork(_ network: NetworkType) -> web3 {
        let web3: web3
        switch network {
        case .rinkeby: web3 = Web3.InfuraRinkebyWeb3()
        case .mainnet: web3 = Web3.InfuraMainnetWeb3()
        case .ropsten: web3 = Web3.InfuraRopstenWeb3()
        default:
            let endpoint = "https://some.endpoint"
            web3 = try! Web3.new(URL(string: endpoint)!)
        }
        return web3
    }
}
